<script setup lang="ts">
import { ElMessage, UploadRequestOptions } from "element-plus"
import { Download, View } from "@element-plus/icons-vue"
import { onMounted, ref, unref, watch } from "vue"
import previewPdf from "@/components/PreviewPdf/index.vue"

import { getResumeFile } from "@/api/user"
import { uploadFile } from "@/api/file"

const resumeUrl = ref<string>()

// #region 上传和获取简历
const uploadRef = ref()
const resumeFileRef = ref()
const previewPdfRef = ref()

function handleUploadResume(opts: UploadRequestOptions) {
  const { file } = opts
  const form = new FormData()
  form.append("file", file)
  form.append("biz", "user_profile")
  return uploadFile(form)
}

function handleUploadResumeSuccess(response: ApiResponseData<string>) {
  uploadRef.value?.clearFiles()
  ElMessage({ type: "success", message: "上传成功" })
  const { data } = response
  resumeUrl.value = data
}

function submitResumeFile() {
  uploadRef.value?.submit()
}

function openPdfFile() {
  if (resumeUrl.value) {
    previewPdfRef.value?.handleOpenResumePdf(resumeUrl.value)
  }
}

watch(
  () => resumeUrl.value,
  (cur) => {
    if (cur) {
      unref(resumeFileRef).classList.add("is")
    } else {
      unref(resumeFileRef).classList.remove("is")
    }
  }
)

onMounted(() => {
  getResumeFile().then(({ data }) => {
    resumeUrl.value = data
  })
})

// #endregion
</script>

<template>
  <div class="app-container">
    <el-card class="resume-upload-file" shadow="never">
      <el-upload
        ref="uploadRef"
        class="resume-uploader"
        action="#"
        accept=".pdf"
        :http-request="handleUploadResume"
        :auto-upload="false"
        :limit="1"
        :on-success="handleUploadResumeSuccess"
      >
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template>
        <el-button class="ml-3" type="success" @click="submitResumeFile">上传简历</el-button>
        <template #tip>
          <div class="el-upload__tip">pdf 文件大小少于等于 5000KB</div>
        </template>
      </el-upload>
    </el-card>
    <el-card class="resume-upload-preview" body-class="resume-file-wrapper" shadow="never">
      <div ref="resumeFileRef" class="resume-file">
        <div class="resume-file__opts">
          <el-button text :icon="View" @click="openPdfFile" />
          <el-button text :icon="Download" />
        </div>
        <div class="resume-file__mark">暂未上传简历</div>
      </div>
    </el-card>
    <teleport to="body">
      <preview-pdf ref="previewPdfRef" />
    </teleport>
  </div>
</template>

<style scoped lang="scss" src="./style.scss"></style>
